package com.example.toycarcontroller

import android.app.Application
import android.bluetooth.BluetoothManager
import android.bluetooth.BluetoothProfile
import android.content.Context
import android.os.Bundle
import android.content.pm.ActivityInfo
import androidx.appcompat.app.AppCompatActivity
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.Observer
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.AndroidViewModel
import android.util.Log
import androidx.gridlayout.widget.GridLayout

/**
 * 观察LiveData仅一次
 */
fun <T> LiveData<T>.observeOnce(owner: LifecycleOwner, observer: Observer<T>) {
    observe(owner, object : Observer<T> {
        override fun onChanged(value: T) {
            removeObserver(this)
            observer.onChanged(value)
        }
    })
}

class DebugActivity : AppCompatActivity() {
    private lateinit var sharedViewModel: SharedViewModel
    private lateinit var bluetoothService: BluetoothService
    private val TAG = "DebugActivity"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
        setContentView(R.layout.activity_debug)
        Log.d(TAG, "DebugActivity onCreate")

        // 使用单例ViewModel
        sharedViewModel = SharedViewModel.getInstance(application as Application)

        // 添加状态日志
        val currentStatus = sharedViewModel.bluetoothStatus.value
        Log.d(TAG, "当前蓝牙状态: 已连接=${currentStatus?.isConnected}, 设备=${currentStatus?.deviceName}")

        // 初始化UI状态
        updateIndicator(currentStatus?.isConnected ?: false)

        // 添加详细的观察日志
        sharedViewModel.bluetoothStatus.observe(this) { status ->
            Log.d(TAG, "观察到蓝牙状态变化: 已连接=${status.isConnected}, 设备=${status.deviceName}")

            // 更新UI显示
            updateIndicator(status.isConnected)
        }

        // 新增视图引用及事件绑定
        val btnForward = findViewById<Button>(R.id.btn_forward)
        val btnBackward = findViewById<Button>(R.id.btn_backward)
        val tvInfoDisplay = findViewById<TextView>(R.id.tv_info_display)
        val btnUpArrow = findViewById<Button>(R.id.btn_up_arrow)
        val btnDownArrow = findViewById<Button>(R.id.btn_down_arrow)

        btnForward.setOnClickListener {
            // 处理正方向逻辑
            Log.d(TAG, "正方向按钮被点击")
        }

        btnBackward.setOnClickListener {
            // 处理反方向逻辑
            Log.d(TAG, "反方向按钮被点击")
        }

        btnUpArrow.setOnClickListener {
            // 处理上箭头逻辑
            Log.d(TAG, "上箭头按钮被点击")
        }

        btnDownArrow.setOnClickListener {
            // 处理下箭头逻辑
            Log.d(TAG, "下箭头按钮被点击")
        }

        // 修改：使用单例获取蓝牙服务
        bluetoothService = BluetoothService.getInstance(this)
        // 添加服务观察
        sharedViewModel.bluetoothServices.observe(this) { services ->
            services?.forEach { service ->
                Log.d(TAG, "发现服务: ${service.uuid}")
            }
        }

    }

    override fun onDestroy() {
        // 移除所有按钮点击监听器
        findViewById<Button>(R.id.btn_forward).setOnClickListener(null)
        findViewById<Button>(R.id.btn_backward).setOnClickListener(null)
        findViewById<Button>(R.id.btn_up_arrow).setOnClickListener(null)
        findViewById<Button>(R.id.btn_down_arrow).setOnClickListener(null)
        
        // 清空所有回调
        bluetoothService.setConnectionStateCallback(null)
        bluetoothService.setServiceDiscoveryCallback(null)
        
        super.onDestroy()
    }

    private fun updateIndicator(isConnected: Boolean) {
        val ivLeftIndicator = findViewById<ImageView>(R.id.iv_left_indicator)
        ivLeftIndicator.setBackgroundResource(
            if (isConnected) R.drawable.ic_indicator_on
            else R.drawable.ic_indicator_off
        )
    }

}